package com.suke.czx.modules.wx.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.suke.czx.common.utils.JsonResult;
import com.suke.czx.modules.wx.config.WxMpConfiguration;
import com.suke.czx.modules.wx.cons.Constant;
import com.suke.czx.modules.wxadmin.entity.DkDomianEntity;
import com.suke.czx.modules.wxadmin.entity.DkDomianReadEntity;
import com.suke.czx.modules.wxadmin.entity.DkUserEntity;
import com.suke.czx.modules.wxadmin.service.DkDomianReadService;
import com.suke.czx.modules.wxadmin.service.DkUserService;

import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

@Controller
@RequestMapping("/wx/base/{appid}")
public class WxBaseController extends BaseController{
	
	
	private org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
    private DkUserService dkUserService;
	
	@Autowired 
	private DkDomianReadService dkDomianReadService;
	
	@RequestMapping(value="/rout")
	public String r(@PathVariable String appid,@RequestParam(defaultValue="pay|1|1")String p ,String code , String state){
		//http://dk2019.hbanbao.com/x_springboot/wx/redirect/wx110e4b18284caf04?url=http://hbanbao.com/index2.html?p=pay_1_1&isshow=1
		//http://dk2019.hbanbao.com/index.html?hash=pay&code=081kSHCl1j5qJo0ZMeCl1eVyCl1kSHCU&state=986472422#/pay
		String strs[] = p.split("_");
		if(strs[0].equals("pay")){
			return "redirect:https://dk2030.hbanbao.com/index.html?hash="+strs[0]+"&courseId="+strs[1]+"&dis="+strs[2]+"&code="+code+"&state="+state+"#/pay";
		}
		
//		if(strs[0].equals("read")){
//			return "redirect:http://dk2031.hbanbao.com/index.html?hash="+strs[0]+"&courseId="+strs[1]+"&dis="+strs[2]+"&code="+code+"&state="+state+"#/"+strs[0];
//		}
		

		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("page", 1);
		params.put("limit", 1000);
		List<DkDomianReadEntity> domains  = dkDomianReadService.queryList(params);
		int r = (int)(Math.random()*domains.size());
    	String domain = domains.get(r).getDomainName().trim();
		return "redirect:https://"+domain+"/index.html?hash="+strs[0]+"&courseId=1"+"&code="+code+"&state="+state+"#/"+strs[0];
	}	
	/**
	 * 获取js API 签名
	 * @param url
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/js/sign")
	@ResponseBody
	public String getJsSign(@PathVariable String appid,String url ){
		
		url = url.replace("amp;", "");
		
		WxMpService wxMpService = WxMpConfiguration.getMpServices().get(appid);
		//wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);		
		try {
			WxJsapiSignature sign = wxMpService.createJsapiSignature(url);
			return new JsonResult(200,"ok",sign).toJson();
		} catch (WxErrorException e) {
			e.printStackTrace();
			return new JsonResult(-1,"签名失败！").toJson();
		}
		
	}
	
	@RequestMapping(value="/login")
	@ResponseBody
	public String login2ById(@PathVariable String appid,String code, String state) {
		
		WxMpUser wxMpUser = (WxMpUser) getSession().getAttribute(Constant.WX_USER);
		if(null!=wxMpUser){
			DkUserEntity dkUser = dkUserService.queryObject(wxMpUser.getOpenId());
			return new JsonResult(200,"已经登录就不需要登录",dkUser).toJson();
		}
		//判断 code 和 state 是否为空
		if(StringUtils.isEmpty(code)){
			return new JsonResult(-1,"code参数获取失败，请重新刷新页面！").toJson();
		}
		
		
		WxMpService wxMpService = WxMpConfiguration.getMpServices().get(appid);
		try {
			WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
			wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
			if(null==wxMpUser){
				return new JsonResult(-1,"登录异常").toJson();
			}
			//保存登录用户信息到session，后期需要改造分布式
			getSession().setAttribute(Constant.WX_USER, wxMpUser);
			//判断用户是否存在
			DkUserEntity dkUser = dkUserService.queryObject(wxMpUser.getOpenId());
			if(null==dkUser){
				dkUser = new DkUserEntity();
				dkUser.setOpenid(wxMpUser.getOpenId());
				dkUser.setCreatetime(new Date());
				dkUser.setHeadimg(wxMpUser.getHeadImgUrl());
				dkUser.setNickname(wxMpUser.getNickname());
				dkUser.setState(0);
				
				dkUserService.save(dkUser);
				
			}else{
				if(StringUtils.isEmpty(dkUser.getNickname())){
					dkUser.setOpenid(wxMpUser.getOpenId());
					dkUser.setUpdatetime(new Date());
					dkUser.setHeadimg(wxMpUser.getHeadImgUrl());
					dkUser.setNickname(wxMpUser.getNickname());
					dkUserService.update(dkUser);
				}
			}
			//TODO 保存用户 以便后续规划
			return new JsonResult(200,"ok",dkUser).toJson();
		} catch (WxErrorException e) {
			logger.error("=============>" +  e.getMessage());
			return new JsonResult(-99,"请退出当前页面从公众号菜单重新进入！").toJson();
		}
	}
	
	
}
